//
//  RequestService+.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/27.
//

import UIKit
import Alamofire
import Swime
 
extension RequestService {
 
    func imageDataList(completeClosure: ((PaintingModel) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/image/data_list",
                        method: .post,
                        parameters: ["timestamp":time, "sign":sign], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let data = result["data"] as? [String: Any], let model = PaintingModel.deserialize(from: data) else { return }
                completeClosure?(model)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func imageCreate(message:String, negativePrompt:String, style_id:Int,proportion_id:Int, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/image/create",
                        method: .post,
                        parameters: ["timestamp":time, 
                                     "sign":sign,
                                     "message":message,
                                     "negativePrompt":negativePrompt,
                                     "style_id":style_id,
                                     "proportion_id":proportion_id
                                    ], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let checkId = result["checkId"] as? String else { return }
                completeClosure?(checkId)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func getCheckImage(checkId:String, completeClosure: ((PaintImageDataModel?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "checkId":checkId])
        session.request("\(apiHost)/api/image/getImages",
                        method: .post,
                        parameters: ["timestamp":time,
                                     "sign":sign,
                                     "checkId":checkId
                                    ], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? String else { return } 
                if var decrypt = result.decryptWithAES(key: decrypt_key, iv: decrypt_key) {
                    decrypt = trimmingAllWhitespace(str: decrypt);
                    decrypt = decrypt.replacingOccurrences(of: "null", with: "\"null\"")
                    decrypt = decrypt.replacingOccurrences(of: "\0", with: "")
                    XLog.d("", decrypt)
                    if let jsonData = decrypt.data(using: .utf8) {
                        let JSON = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
                        if let decryptJson = JSON as? [String: Any], let model = PaintImageDataModel.deserialize(from: decryptJson) {
                            completeClosure?(model)
                        }
                    }else {
                        completeClosure?(nil)
                    }
                }else {
                    failureClosure?("error")
                }
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
}
